import React, { memo, useEffect, useState } from "react";
import { useDispatch } from "react-redux";
import { useLocation, useNavigate } from "react-router-dom";
import { Input, List, NavBar, Grid } from "antd-mobile";
import queryString from "query-string";
import { ChatWrapper } from "./style.js";
import { getChatId } from "@/utils/util";
import store from "@/store/index.js";
import uploadFile from "./uploadFile.js";
import {
  fetchChatlist,
  fetchReadMsg,
  fetchSendMsg,
} from "@/store/modules/chat.js";
import { useRef } from "react";
import { picBaseUrl } from "@/utils/constant.js";

const Chat = memo((props) => {
  const navigate = useNavigate();
  const location = useLocation();
  const dispath = useDispatch();

  let [allList, setAllList] = useState(store.getState().chat.chatmsg);
  let [users, setusers] = useState(store.getState().chat.users);
  let [value, setValue] = useState("");
  let [showEmoji, setShowEmoji] = useState(false);
  let [footerHeight, setFooterHeight] = useState(50);

  let query = queryString.parse(location.search);
  let toUserid = query.id;
  let username = query.user;
  let fromUserid = store.getState().user._id;
  let currentChatId = getChatId(toUserid, fromUserid);
  let allListLen = allList.length;

  useEffect(() => {
    // 当chatmsg为长度0的时候 才获取数
    if (!allListLen) {
      dispath(fetchChatlist()).then((res) => {
        let data = res.payload.data;
        setAllList(data.data);
        setusers(data.users);
      });
    } else {
      let filterMsg = allList.filter((v) => v.chatid === currentChatId);
      chatMsg = filterMsg;
    }
    const unsubscribe = store.subscribe(() => {
      setAllList(store.getState().chat.chatmsg);
      setusers(store.getState().chat.users);
    });

    return () => {
      dispath(fetchReadMsg(toUserid));
      unsubscribe();
    };
  }, []);

  useEffect(() => {
    if (allList.length) {
      let filterList = allList.filter((v) => v.chatid === currentChatId);
      chatMsg = filterList;
    }
  }, [allList]);

  useEffect(() => {
    if (showEmoji) {
      setFooterHeight(260);
    } else {
      setFooterHeight(50);
    }
  }, [showEmoji]);
  const emoji =
    "😀 😃 😄 😁 😆 😅 😂 😊 😇 🙂 🙃 😉 😌 😍 😘 😗 😙 😚 😋 😜 😝 😛 🤑 🤗 🤓 😎 😏 😒 😞 😔 😟 😕 🙁 😣 😖 😫 😩 😤 😠 😡 😶 😐 😑 😯 😦 😧 😮 😲 😵 😳 😱 😨 😰 😢 😥 😭 😓 😪 😴 🙄 🤔 😬 🤐 😷 🤒 🤕 😈 👿 👹 👺 💩 👻 💀 ☠️ 👽 👾 🤖 🎃 😺 😸 😹 😻 😼 😽 🙀 😿 😾 👐 🙌 👏 🙏 👍 👎 👊 ✊ 🤘 👌 👈 👉 👆 👇 ✋  🖖 👋  💪 🖕 ✍️  💅  💄 💋 👄 👅 👂 👃 👁 👀 "
      .split(" ")
      .filter((v) => v)
      .map((v) => ({ text: v }));
  // 在chat页面刷新，会丢失redux数据
  if (!fromUserid) {
    navigate("/login");
  }

  function back() {
    navigate(-1);
  }

  function handleSubmit() {
    console.log("handlesubmit");
    dispath(fetchSendMsg({ fromUserid, toUserid, value })).then((res) => {
      let list = store.getState().chat.chatmsg;
      setAllList(list);
    });
    setValue("");
    setShowEmoji(false);
  }

  function submitFile() {
    uploadFile()
      .then((res) => {
        // console.log(res);
        dispath(fetchSendMsg({ fromUserid, toUserid, value: res.data })).then(
          (res) => {
            let list = store.getState().chat.chatmsg;
            setAllList(list);
          }
        );
        setValue("");
        setShowEmoji(false);
      })
      .catch((err) => {});
  }

  function downloadFile(fileName) {
    const a = document.createElement("a");
    a.href = `${picBaseUrl}/${fileName}`;
    let realName = fileName.slice(19);
    a.download = `${realName}`;
    a.click();
    a.remove();
  }

  let chatMsg = allList.filter((v) => v.chatid === currentChatId);

  return (
    <ChatWrapper footerHeight={footerHeight}>
      <div className="chat-page">
        <NavBar
          mode="dark"
          back="返回"
          onBack={back}
          className="navbarCls"
          style={{ backgroundColor: "#108ee9", color: "white" }}
        >
          {username}
        </NavBar>

        <div
          className="main"
          onClick={() => {
            setShowEmoji(false);
          }}
        >
          {chatMsg.map((v) => {
            let avatar = "";
            try {
              avatar = require(`../../components/img/${
                users[v.from].avatar
              }.png`);
            } catch (error) {
              // 如果图片出错，使用默认的头像

              avatar = require(`../../components/img/default.png`);
            }

            // 我发送的
            // return v.from === fromUserid ? (
            //   <List key={v._id} className="mysend">
            //     <List.Item
            //       extra={
            //         avatar && <img src={avatar} style={{ width: 50 }} alt="" />
            //       }
            //     >
            //       {v.content}
            //     </List.Item>
            //   </List>
            // ) : (
            //   <List key={v._id}>
            //     <List.Item
            //       prefix={
            //         avatar && <img src={avatar} style={{ width: 50 }} alt="" />
            //       }
            //     >
            //       {v.content}
            //     </List.Item>
            //   </List>
            // );

            return (
              <List key={v._id} className="mysend">
                <List.Item
                  extra={
                    v.from === fromUserid &&
                    avatar && <img src={avatar} style={{ width: 50 }} alt="" />
                  }
                  prefix={
                    v.from !== fromUserid &&
                    avatar && <img src={avatar} style={{ width: 50 }} alt="" />
                  }
                >
                  {/* <div>{v.content}</div> */}
                  {v.content.startsWith("file_") ? (
                    <div
                      className="fileCls"
                      onClick={() => downloadFile(v.content)}
                      style={{
                        textAlign: v.from != fromUserid ? "left" : "right",
                        textOverflow: "ellipsis",
                        overflow: "hidden",
                      }}
                    >
                      <i className="iconfont icon-file"></i>
                      {v.content.slice(19)}
                    </div>
                  ) : (
                    <div
                      style={{
                        textAlign: v.from != fromUserid ? "left" : "right",
                        textOverflow: "ellipsis",
                        overflow: "hidden",
                      }}
                    >
                      {v.content}
                    </div>
                  )}
                </List.Item>
              </List>
            );
          })}
        </div>

        <div className="footer">
          <List>
            <List.Item
              extra={
                <div>
                  <span>
                    <i
                      className="iconfont icon-file"
                      onClick={(e) => {
                        e.stopPropagation();
                        submitFile();
                      }}
                    ></i>
                    {/* <input type="file" /> */}
                  </span>

                  <span
                    style={{ fontSize: 12, marginRight: 15 }}
                    onClick={() => {
                      setShowEmoji(!showEmoji);
                    }}
                  >
                    😃
                  </span>
                  <span onClick={() => handleSubmit()}>发送</span>
                </div>
              }
            >
              <Input
                onFocus={() => {
                  setShowEmoji(true);
                }}
                placeholder="请输入"
                value={value}
                onChange={(v) => {
                  setValue(v);
                }}
              ></Input>
            </List.Item>
          </List>
          {showEmoji ? (
            <Grid columns={9} gap={8} className="emojiCon">
              {emoji.map((item) => {
                return (
                  <Grid.Item
                    key={item.text}
                    onClick={(e) => {
                      setValue(value + e.target.innerText);
                    }}
                  >
                    <div>{item.text}</div>
                  </Grid.Item>
                );
              })}
            </Grid>
          ) : null}
        </div>
      </div>
    </ChatWrapper>
  );
});

export default Chat;
